package com.yesorno.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.yesorno.constants.Constants;
import com.yesorno.model.HttpResponseObject;
import com.yesorno.ui.CustomTitleActivity;
import com.yesorno.ui.MyMenuList;
import com.yesorno.utils.HttpUtils;

public class TopicListActivity extends CustomTitleActivity {

	private Button topic_list_publish;
	private Button topic_list_refresh;
	private Button topic_list_top_join;
	private Button topic_list_top_discuss;
	private Button topic_list_top_message;

	private ListView topic_list_listview;

	private LinearLayout topic_list_top;

	private long curUserId;

	String type;// intent对应的type，如果为null，则代表为信息，如果为join则为加入的话题，如果为publish则为发布的话题
	ImgSimpleAdapter adapter;
	List<Map<String, Object>> list;// listview对应的结果集
	int selectIndex;// 在信息的模块里的自分类，包括 话题、评论、私信

	RegBtnsClickListeners rbc = new RegBtnsClickListeners();

	/**
	 * 注册页面按钮的监听类
	 * 
	 * @author samoin
	 * @date 2011-07-06
	 * @version 0.1
	 * 
	 */
	class RegBtnsClickListeners implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (v == topic_list_publish) {
				Intent intent = new Intent();
				TopicListActivity.this.setResult(RESULT_OK, intent);
				TopicListActivity.this.finish();
			}
			if (v == topic_list_top_join) {
				setTopicList();
			}
			if (v == topic_list_top_discuss) {
				setCommentList();
			}
			if (v == topic_list_top_message) {
				setMessageList();
			}
			if (v == topic_list_refresh) {// 刷新按钮，我草，有N种情况，MB
				if (type == null || type.equals("")) {// 信息
				}
			}
		}

	}

	// 在信息中点击参与的话题
	private void setTopicList() {
		resetBtnList(0);
		deleteListChild(list, adapter, topic_list_listview);
		String url = Constants.TOPIC_PUBLIC_LIST_URL;
		if (type != null && type.equals("join")) {// 参与的话题
			url = Constants.TOPIC_JOIN_LIST_URL;
		}
		if (type == null || type.equals("")) {// 信息
			url = Constants.TOPIC_JOIN_LIST_URL;
		}
		// TODO 获取该用户的对应的发布或关注的列表
		HttpResponseObject hro = HttpUtils.getInfoByUrlPost(url + "userId="
				+ curUserId, TopicListActivity.this);
		list = new ArrayList<Map<String, Object>>();
		try {
			JSONArray array = hro.getResult().getJSONArray("topicList");
			for (int i = 0; i < array.length(); i++) {
				JSONObject jsonObject = array.getJSONObject(i);
				Map<String, Object> map = new HashMap<String, Object>();
				Long userId = jsonObject.getLong("userId");
				Long topicId = jsonObject.getLong("topicId");
				String from = Constants.INFO_FROM_MAP.get(""
						+ jsonObject.getInt("from"));
				int countYes = jsonObject.getInt("countYes");
				int countNo = jsonObject.getInt("countNo");
				String userName = jsonObject.getString("userName");
				String publishTime = jsonObject.getString("publishTime");
				String desc = jsonObject.getString("desc");
				String userLogo = jsonObject.getString("userLogo");
				String img = jsonObject.getString("img");
				map.put("topic_list_list_userid", userId);
				map.put("topic_list_list_topicid", topicId);
				map.put("topic_list_list_from", from);
				map.put("topic_list_list_countyes", countYes);
				map.put("topic_list_list_countno", countNo);
				map.put("topic_list_list_username", userName);
				map.put("topic_list_list_publishtime", publishTime);
				map.put("topic_list_list_desc", desc);
				map.put("topic_list_list_userlogo", userLogo);
				map.put("topic_list_list_img", img);
				list.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		adapter = new ImgSimpleAdapter(
				TopicListActivity.this,
				list,
				R.layout.topic_list_list,
				new String[] { "topic_list_list_userid",
						"topic_list_list_topicid", "topic_list_list_from",
						"topic_list_list_countno", "topic_list_list_countyes",
						"topic_list_list_username",
						"topic_list_list_publishtime", "topic_list_list_desc",
						"topic_list_list_userlogo", "topic_list_list_img" },
				new int[] { R.id.topic_list_list_userid,
						R.id.topic_list_list_topicid,
						R.id.topic_list_list_from,
						R.id.topic_list_list_countno,
						R.id.topic_list_list_countyes,
						R.id.topic_list_list_username,
						R.id.topic_list_list_publishtime,
						R.id.topic_list_list_desc,
						R.id.topic_list_list_userlogo, R.id.topic_list_list_img });
		topic_list_listview.setAdapter(adapter);
	}

	// 在信息中点击私信
	private void setMessageList() {
		resetBtnList(2);
		deleteListChild(list, adapter, topic_list_listview);
		// TODO 获取该用户的对应的发布或关注的列表
		HttpResponseObject hro = HttpUtils.getInfoByUrlPost(
				Constants.USER_MESSAGE_LIST_URL + "userId=" + curUserId,
				TopicListActivity.this);
		try {
			JSONArray array = hro.getResult().getJSONArray("list");
			list = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < array.length(); i++) {
				JSONObject jsonObject = array.getJSONObject(i);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user_message_list_logo", jsonObject.get("userLogo"));
				map.put("user_message_list_username",
						jsonObject.get("userName"));
				map.put("user_message_list_time", jsonObject.get("publishTime"));
				map.put("user_message_list_desc", jsonObject.get("desc"));
				map.put("user_message_list_userid", jsonObject.get("userId"));
				map.put("user_message_list_messageid",
						jsonObject.get("messageId"));
				list.add(map);
			}
			adapter = new ImgSimpleAdapter(TopicListActivity.this, list,
					R.layout.user_message_list_list, new String[] {
							"user_message_list_logo",
							"user_message_list_username",
							"user_message_list_time", "user_message_list_desc",
							"user_message_list_userid",
							"user_message_list_messageid" }, new int[] {
							R.id.user_message_list_logo,
							R.id.user_message_list_username,
							R.id.user_message_list_time,
							R.id.user_message_list_desc,
							R.id.user_message_list_userid,
							R.id.user_message_list_messageid });
			topic_list_listview.setAdapter(adapter);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	// 在信息中点击评论
	private void setCommentList() {
		resetBtnList(1);
		deleteListChild(list, adapter, topic_list_listview);
		// TODO 获取该用户的对应的发布或关注的列表
		HttpResponseObject hro = HttpUtils.getInfoByUrlPost(
				Constants.USER_COMMENT_LIST_URL + "userId=" + curUserId,
				TopicListActivity.this);
		try {
			JSONArray array = hro.getResult().getJSONArray("list");
			list = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < array.length(); i++) {
				JSONObject jsonObject = array.getJSONObject(i);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user_comment_list_logo", jsonObject.get("userLogo"));
				map.put("user_comment_list_username",
						jsonObject.get("userName"));
				map.put("user_comment_list_time", jsonObject.get("editTime"));
				map.put("user_comment_list_desc", jsonObject.get("desc"));
				map.put("user_comment_list_commenttopicname",
						jsonObject.get("topicName"));
				map.put("user_comment_list_userid", jsonObject.get("userId"));
				map.put("user_comment_list_commentid",
						jsonObject.get("commentId"));
				map.put("user_comment_list_topicid", jsonObject.get("topicId"));
				map.put("user_comment_list_commenttype",
						jsonObject.get("commentType"));
				list.add(map);
			}
			adapter = new ImgSimpleAdapter(TopicListActivity.this, list,
					R.layout.user_comment_list_list, new String[] {
							"user_comment_list_logo",
							"user_comment_list_username",
							"user_comment_list_time", "user_comment_list_desc",
							"user_comment_list_commenttopicname",
							"user_comment_list_userid",
							"user_comment_list_commentid",
							"user_comment_list_topicid",
							"user_comment_list_commenttype" }, new int[] {
							R.id.user_comment_list_logo,
							R.id.user_comment_list_username,
							R.id.user_comment_list_time,
							R.id.user_comment_list_desc,
							R.id.user_comment_list_commenttopicname,
							R.id.user_comment_list_userid,
							R.id.user_comment_list_commentid,
							R.id.user_comment_list_topicid,
							R.id.user_comment_list_commenttype });
			topic_list_listview.setAdapter(adapter);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 重置按钮的选中状态
	 * 
	 * @param index
	 */
	private void resetBtnList(int index) {
		selectIndex = index;
		for (int i = 0; i < topic_list_top.getChildCount(); i++) {
			Button btn = (Button) topic_list_top.getChildAt(i);
			if (index == i) {
				btn.setBackgroundResource(R.drawable.common_btn_white);
			} else {
				btn.setBackgroundResource(R.drawable.white_disabled_btn);
			}
		}
	}

	@Override
	public void setTitleViews() {
		LinearLayout titleLayout = getTITLE_LAYOUT();
		type = getIntent().getStringExtra("topicType");// 类型

		if (type == null || type.equals("")) {// 信息
			TextView tv2 = CustomTitleActivity.createTitleDesc(
					TopicListActivity.this, 0, 0);
			titleLayout.addView((View) tv2.getParent());
		} else {
			// 发布按钮
			topic_list_publish = CustomTitleActivity.createTitleLeftButton(
					TopicListActivity.this, R.string.topic_list_publish,
					Constants.TITLE_BTN_MARGIN1);
			topic_list_publish.setOnClickListener(rbc);
			titleLayout.addView((View) topic_list_publish.getParent());
		}

		int titleId = R.string.topic_list_title_publish;
		topic_list_top = (LinearLayout) findViewById(R.id.topic_list_top);
		if (type != null && type.equals("join")) {
			titleId = R.string.topic_list_title_join;
		}
		if (type == null || type.equals("")) {
			titleId = R.string.info_title;
			topic_list_top.setVisibility(View.VISIBLE);
		}
		// 中间的资料的文字
		TextView tv = CustomTitleActivity.createTitleDesc(
				TopicListActivity.this, titleId, 0);
		titleLayout.addView((View) tv.getParent());

		topic_list_refresh = CustomTitleActivity.createTitleRightButton(
				TopicListActivity.this, R.string.topic_list_refresh,
				Constants.TITLE_BTN_MARGIN2);
		topic_list_refresh.setOnClickListener(rbc);
		titleLayout.addView((View) topic_list_refresh.getParent());
	}

	@Override
	public void setLayoutId() {
		setContentView(R.layout.topic_list);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		curUserId = getIntent().getLongExtra("userId", 0);
		super.onCreate(savedInstanceState);
		int index = 0;
		if (type == null || type.equals("")) {
			index = 1;
		}
		((LinearLayout) findViewById(R.id.menus)).addView(new MyMenuList(
				TopicListActivity.this, index));
		setMyView();
		setTopicList();
	}

	private void setMyView() {
		topic_list_listview = (ListView) findViewById(R.id.topic_list_listview);
		// 这句代码非常重要，用来设置点击的当前项的背景
		topic_list_listview.setSelector(R.drawable.list_bg);
		// 这句代码非常重要，用来设置拖动中的背景
		topic_list_listview.setCacheColorHint(0);

		topic_list_listview.setOnItemClickListener(new MyOnItemClickListener());

		topic_list_top_join = (Button) findViewById(R.id.topic_list_top_join);
		topic_list_top_discuss = (Button) findViewById(R.id.topic_list_top_discuss);
		topic_list_top_message = (Button) findViewById(R.id.topic_list_top_message);
		topic_list_top_join.setOnClickListener(rbc);
		topic_list_top_discuss.setOnClickListener(rbc);
		topic_list_top_message.setOnClickListener(rbc);
	}

	// 点击大厅列表中的某行
	class MyOnItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if (type == null || type.equals("")) {
				if (selectIndex == 0) {
					clickTopic(arg1);
				}
				if (selectIndex == 1) {
					clickComment(arg1);
				}
				if (selectIndex == 2) {
					clickMessage(arg1);
				}
			} else {
				clickTopic(arg1);
			}

		}

		public void clickComment(View arg1) {
			Intent intent = new Intent();
			TextView idTv = (TextView) arg1
					.findViewById(R.id.user_comment_list_topicid);
			TextView idTv2 = (TextView) arg1
					.findViewById(R.id.user_comment_list_userid);
			intent.putExtra("currentTopicId", Long.valueOf(idTv.getText() + ""));
			intent.putExtra("currentUserId", Long.valueOf(idTv2.getText() + ""));
			intent.setClass(TopicListActivity.this,
					UserCommentMenuActivity.class);
			startActivity(intent);
		}

		public void clickMessage(View arg1) {
			Intent intent = new Intent();
			TextView idTv = (TextView) arg1
					.findViewById(R.id.user_message_list_messageid);
			TextView idTv2 = (TextView) arg1
					.findViewById(R.id.user_message_list_userid);
			intent.putExtra("currentMessageId",
					Long.valueOf(idTv.getText() + ""));
			intent.putExtra("currentUserId", Long.valueOf(idTv2.getText() + ""));
			intent.setClass(TopicListActivity.this,
					UserMessageMenuActivity.class);
			startActivityForResult(intent, 0);
		}

		public void clickTopic(View arg1) {
			Intent intent = new Intent();
			TextView idTv = (TextView) arg1
					.findViewById(R.id.topic_list_list_topicid);
			TextView idTv2 = (TextView) arg1
					.findViewById(R.id.topic_list_list_userid);
			intent.putExtra("currentTopicId", Long.valueOf(idTv.getText() + ""));
			intent.putExtra("currentUserId", Long.valueOf(idTv2.getText() + ""));
			intent.setClass(TopicListActivity.this, HallMenuActivity.class);
			startActivity(intent);
		}

	}

	/**
	 * 菜单回传的处理
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			String type = data.getStringExtra("type");
			String selectIndexGroup = data.getStringExtra("selectIndexGroup");
			if (type != null && type.equals("delall")) {
				if (selectIndexGroup.length() > 0) {
					String[] array = selectIndexGroup.split(",");
					List<Map<String, Object>> temp = new ArrayList<Map<String, Object>>();
					for (int i = 0; i < array.length; i++) {
						temp.add(list.get(Integer.valueOf(array[i]).intValue()));
					}
					for (int i = 0; i < temp.size(); i++) {
						list.remove(temp.get(i));
					}
					adapter.notifyDataSetChanged();
					topic_list_listview.invalidate();
				}
			}
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);

	}

	class ImgSimpleAdapter extends CustomTitleActivity.ImgSimpleAdapter {

		public ImgSimpleAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
		}

		@Override
		public void setViewText(TextView v, String text) {
			super.setViewText(v, text);
			if (v.getId() == R.id.topic_list_list_from) {
				String from = getResources()
						.getString(R.string.topic_list_from) + text;
				v.setText(from);
			}
			if (v.getId() == R.id.topic_list_list_countyes) {
				String countYes = getResources().getString(
						R.string.topic_list_yes).replace("$1", text);
				v.setText(countYes);
			}
			if (v.getId() == R.id.topic_list_list_countno) {
				String countNo = getResources().getString(
						R.string.topic_list_no).replace("$1", text);
				v.setText(countNo);
			}
			if (v.getId() == R.id.user_comment_list_commenttype) {
				if (text.equals(Constants.COMMENT_TYPE_YES + "")) {
					v.setText(getResources().getString(
							R.string.view_comment_type_yes));
					v.setBackgroundResource(R.drawable.common_btn_bg_green);
					v.setTextColor(getResources().getColor(R.color.black));
				}
				if (text.equals(Constants.COMMENT_TYPE_NO + "")) {
					v.setText(getResources().getString(
							R.string.view_comment_type_no));
					v.setBackgroundResource(R.drawable.common_btn_bg_red);
					v.setTextColor(getResources().getColor(R.color.white));
				}
			}
			if (v.getId() == R.id.user_comment_list_time) {
				v.setText(getResources().getString(R.string.user_comment_time)
						+ text);
			}
			if (v.getId() == R.id.user_comment_list_commenttopicname) {
				String temp = getResources().getString(
						R.string.user_comment_comment)
						+ text;
				temp = temp.length() > Constants.USER_COMMENT_TOPICNAME_LEN ? (temp
						.substring(0, Constants.USER_COMMENT_TOPICNAME_LEN) + "……")
						: temp;
				v.setText(temp);
			}
		}
	}

}
